package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.Department;
import com.example.demo.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 分页获取全部科室
     * 示例：GET /department?page=1&size=5
     */
    @GetMapping
    public IPage<Department> listAllDepartments(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size) {
        return departmentService.page(new Page<>(page, size));
    }

    /**
     * 模糊查询科室名称，支持分页
     * 示例：GET /department/search?name=内科&page=1&size=5
     */
    @GetMapping("/search")
    public IPage<Department> searchDepartments(
            @RequestParam("name") String name,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size) {

        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);  // 模糊匹配name字段

        return departmentService.page(new Page<>(page, size), queryWrapper);
    }

    /**
     * 修改科室状态（或更新整个记录）
     * 示例：POST /department/updateStatus
     */
    @PostMapping("/updateStatus")
    public boolean updateStatus(@RequestBody Department department) {
        return departmentService.updateById(department);
    }

    /**
     * 删除科室
     * 示例：DELETE /department/delete/1
     */
    @DeleteMapping("/delete/{id}")
    public boolean deleteById(@PathVariable Integer id) {
        return departmentService.removeById(id);
    }

    /**
     * 新增科室
     * 示例：POST /department/add
     */
    @PostMapping("/add")
    public boolean add(@RequestBody Department department) {
        return departmentService.save(department);
    }
}